package com.sxz.sbs.module.client;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Environment;
import android.text.Layout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.nanchen.compresshelper.CompressHelper;
import com.sxz.sbs.R;
import com.sxz.sbs.app.AppConstant;
import com.sxz.sbs.applibrary.dialog.input.ValueInputBoardDialog;
import com.sxz.sbs.base.BaseActivity;
import com.sxz.sbs.constant.IntentConstant;
import com.sxz.sbs.http.retrofit.HttpParamMap;
import com.sxz.sbs.module.client.bean.ClientDetailsBean;
import com.sxz.sbs.module.client.bean.ContractTypeBean;
import com.sxz.sbs.module.client.bean.SelectStallBean;
import com.sxz.sbs.module.client.presenter.DealEvidencePresenter;
import com.sxz.sbs.module.client.view.DealEvidenceView;
import com.sxz.sbs.module.photo.PhotoViewerActivity;
import com.sxz.sbs.module.photo.PhotoViewerBean;
import com.sxz.sbs.module.sale.mode.ImgBackBean;
import com.sxz.sbs.module.staff.AllParkingActivity;
import com.sxz.sbs.module.web.WebViewActivity;
import com.sxz.sbs.other.FileBean;
import com.sxz.sbs.other.ImageShowAdapter;
import com.sxz.sbs.view.SelfAdaptionGridView;
import com.sxz.sbs.widget.CommonTitle;
import com.tian.photopicker.PhotoPicker;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * @author hp
 * @date 2018/1/12
 * 上传定金合同
 */

public class EvidenceActivity extends BaseActivity<DealEvidencePresenter> implements DealEvidenceView {


    @BindView(R.id.tv_deposit_xq)
    TextView tvDepositXq;
    @BindView(R.id.tv_deposit_stall)
    TextView tvDepositStall;
    @BindView(R.id.tv_deposit_stall_type)
    TextView tvDepositStallType;
    @BindView(R.id.tv_deposit_stall_area)
    TextView tvDepositStallArea;
    @BindView(R.id.tv_deposit_money)
    TextView tvDepositMoney;
    @BindView(R.id.gridView)
    SelfAdaptionGridView gridView;
    @BindView(R.id.submit)
    TextView submit;

    private ImageShowAdapter adapter;
    private List<FileBean> fileList = new ArrayList<>();
    private List<String> urlList = new ArrayList<>();
    private ClientDetailsBean intentBean;
    private String price = "";
    private int parkingId;
    private String stallId;
    private ProgressDialog progressDialog;
    private int deleteIndex;

    @Override
    protected void init() {
        new CommonTitle.Builder(this).setTitle("上传定金凭证").build().show();
        intentBean = getIntent().getParcelableExtra("deal_evidence");
        if (intentBean != null) {
            tvDepositXq.setText(intentBean.getParkingName());
            parkingId = intentBean.getParking_Id();

        }
        adapter = new ImageShowAdapter(this, fileList, 9);
        gridView.setAdapter(adapter);

        adapter.setOnImageShowListener(new ImageShowAdapter.OnImageShowListener() {
            @Override
            public void onImageClick(View v, int position) {
                urlList.clear();
                for (int i = 0; i < fileList.size(); i++) {
                    if (fileList.get(i) != null) {
                        urlList.add(fileList.get(i).getPath());
                    }
                }
                PhotoViewerBean pvb = new PhotoViewerBean(urlList, position);
                startActivity(new Intent(EvidenceActivity.this, PhotoViewerActivity.class)
                        .putExtra(PhotoViewerActivity.PHOTO_VIEWER_TAG, pvb));
            }

            @Override
            public void onImageDelete(View v, int position) {
                deleteIndex = position;
                HashMap<String, Object> map = HttpParamMap.getParamMap();
                map.put("fileId", fileList.get(position).getId());
                mPresenter.deletePhoto(map);
            }

            @Override
            public void onImageAdd(View v, int position) {
                PhotoPicker.builder().setSelectPhotoCount(9 - (fileList.size() - 1)).
                        start(EvidenceActivity.this, 1000);
            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_evidence;
    }

    @Override
    protected DealEvidencePresenter createPresenter() {
        return new DealEvidencePresenter();
    }

    @OnClick({R.id.rl_deposit_xq, R.id.tv_deposit_stall, R.id.tv_deposit_money, R.id.submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_deposit_xq:
                startActivityForResult(new Intent(this, AllParkingActivity.class)
                        .putExtra("from_tag", 5), 1002);
                break;
            case R.id.tv_deposit_stall:
                startActivityForResult(new Intent(this, SelectStallActivity.class)
                                .putExtra("customId", intentBean.getId())
                                .putExtra("parkingId", parkingId)
                                .putExtra("root_in", 1)
                        , 1003);
                break;
            case R.id.tv_deposit_money:
                // TODO 新功能： 加载付款二维码网页，付款后方可提交
//                startActivity(new Intent(this, WebViewActivity.class).putExtra(IntentConstant.WEB_VIEW_URL, QRCodeUrl));

                ValueInputBoardDialog dialog1 = new ValueInputBoardDialog(this, price, ValueInputBoardDialog.UnitEnum.SELL);
                dialog1.setOnDialogResultListener(new ValueInputBoardDialog.OnDialogResultListener() {
                    @Override
                    public void onResult(String value, String unit) {
                        price = value;
                        tvDepositMoney.setText(value + unit);
                        showChosePayType();
                    }
                });
                dialog1.show();
                break;
            case R.id.submit:
                if (TextUtils.isEmpty(stallId)) {
                    ToastUtils.showShort("请选择车位");
                    return;
                }
                if (TextUtils.isEmpty(price)) {
                    ToastUtils.showShort("请输入车位定金");
                    return;
                }
                if (fileList.size() <= 1) {
                    ToastUtils.showShort("请选择定金凭证");
                    return;
                }
                /*if (fileList.size()< 9) {
                    fileList.remove(fileList.size()-1);
                }*/
                String urlString = "";
                for (int i = 0; i < fileList.size(); i++) {
                    if (fileList.get(i) != null) {
                        urlString = urlString + fileList.get(i).getId() + ",";
                    }
                }
                urlString = urlString.substring(0, urlString.length() - 1);
                HashMap<String, Object> map = HttpParamMap.getParamMap();
                map.put("customId", intentBean.getId());
                map.put("spaceId", stallId);
                map.put("money", price);
                map.put("photoId", urlString);
                mPresenter.uploadEvidence(map);
                break;
            default:
                break;
        }
    }

    @Override
    public void onUploadEvidenceSuccess() {
        ToastUtils.showShort("上传成功");
        finish();
    }


    /**
     * 显示选择支付方式dialog
     */
    public void showChosePayType() {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_paytype, null);
        ImageView weixin = view.findViewById(R.id.pay_weixin);
        ImageView zhifubao = view.findViewById(R.id.pay_zhifubao);

        builder.setView(view);
        builder.setTitle(R.string.chose_pay);
        final AlertDialog dialog = builder.create();
        weixin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                ToastUtils.showShort("选择了微信支付！！");
                int money = Integer.valueOf(price)*100;
                String url = AppConstant.WEIXIN_PAY_URL + money;
//                String url = "";
                LogUtils.i("weixin url", url);
                startActivity(new Intent(EvidenceActivity.this, WebViewActivity.class)
                        .putExtra(IntentConstant.WEB_VIEW_URL, url));
                dialog.dismiss();
            }
        });
        zhifubao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastUtils.showShort("支付宝暂未开通，敬请期待！");
                dialog.dismiss();
            }
        });
        dialog.setCancelable(true);
        dialog.show();

    }

    @Override
    public void onUploadFileSuccess(List<ImgBackBean> data) {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
        if (mIsLive && data != null) {
            fileList.remove(fileList.size() - 1);
            for (int i = 0; i < data.size(); i++) {
                fileList.add(new FileBean(data.get(i).getId(), data.get(i).getPhotoUrl()));
            }
            adapter.setNotify(fileList);
        }
    }

    @Override
    public void showError(int errorTag, String msg) {
        super.showError(errorTag, msg);
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

    @Override
    public void onDeleteFileSuccess() {
        fileList.remove(deleteIndex);
        adapter.setNotify(fileList);
    }

    @Override
    public void onGetContractTypeList(List<ContractTypeBean> data) {
    }

    @Override
    public void onGetContractType(ContractTypeBean data) {
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        if (requestCode == 1000) {
            List<String> result = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
            progressDialog = ProgressDialog.show(this, null, "上传中...");
            List<File> fileList = new ArrayList<>();
            for (int i = 0; i < result.size(); i++) {
                if (result.get(i) != null) {
                    File newFile = new CompressHelper.Builder(this)
                            .setMaxWidth(720)
                            .setMaxHeight(1080)
                            .setQuality(90)
                            .setFileName(System.currentTimeMillis() + "" + i)
                            .setCompressFormat(Bitmap.CompressFormat.JPEG)
                            .setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
                                    Environment.DIRECTORY_PICTURES).getAbsolutePath())
                            .build()
                            .compressToFile(new File(result.get(i)));
                    if (newFile != null) {
                        fileList.add(newFile);
                    }
                }
            }
            List<MultipartBody.Part> map = filesToMultipartBodyParts(fileList);
            mPresenter.uploadPhoto(1, map);

        } else if (requestCode == 1002 && resultCode == 1006) {
            parkingId = data.getIntExtra("parking_id", 0);
            tvDepositXq.setText(data.getStringExtra("parking_name"));
        } else if (requestCode == 1003 && resultCode == 1007) {
            SelectStallBean.ListBean bean = data.getParcelableExtra("stall_result");
            if (bean != null) {
                tvDepositStall.setText(TextUtils.isEmpty(bean.getNumber()) ? "无" : bean.getNumber());
                tvDepositStallType.setText(bean.getSpaceTypeName() + "");
                tvDepositStallArea.setText(bean.getSize() + "㎡");
                stallId = bean.getId() + "";
            }
        }
    }

    public List<MultipartBody.Part> filesToMultipartBodyParts(List<File> files) {
        List<MultipartBody.Part> parts = new ArrayList<>(files.size());
        int i = 1;
        for (File file : files) {
            i++;
            RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpg"), file);
            MultipartBody.Part part = MultipartBody.Part.createFormData("fileList" + i, file.getName(), requestBody);
            parts.add(part);
        }
        return parts;
    }
}
